import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { User } from '../models/user.model';

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

interface JwtPayload {
  userId: string;
  role: string;
}

declare global {
  namespace Express {
    interface Request {
      user?: any;
    }
  }
}

export const authMiddleware = {
  // 验证 JWT token
  async authenticate(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const token = req.headers.authorization?.split(' ')[1];
      if (!token) {
        res.status(401).json({ message: '未提供认证令牌' });
        return;
      }

      try {
        const decoded = jwt.verify(token, JWT_SECRET) as JwtPayload;
        const user = await User.findById(decoded.userId).select('-password');
        
        if (!user) {
          res.status(401).json({ message: '用户不存在或已被删除' });
          return;
        }

        req.user = user;
        next();
      } catch (jwtError) {
        if (jwtError instanceof jwt.TokenExpiredError) {
          res.status(401).json({ message: '认证令牌已过期' });
        } else if (jwtError instanceof jwt.JsonWebTokenError) {
          res.status(401).json({ message: '无效的认证令牌' });
        } else {
          res.status(401).json({ message: '认证失败' });
        }
      }
    } catch (error) {
      console.error('认证中间件错误:', error);
      res.status(500).json({ message: '服务器错误' });
    }
  },

  // 验证管理员权限
  requireAdmin(req: Request, res: Response, next: NextFunction): void {
    if (!req.user) {
      res.status(401).json({ message: '未授权访问' });
      return;
    }
    
    if (req.user.role === 'admin') {
      next();
    } else {
      res.status(403).json({ message: '需要管理员权限' });
    }
  },
}; 